package com.duyj.server.stock.service.impl;

import com.duyj.client.stock.model.Stock;
import com.duyj.server.stock.dao.StockDAO;
import com.duyj.server.stock.service.StockService;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StockServiceImpl implements StockService {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(StockServiceImpl.class);

    @Autowired
    private StockDAO stockDAO;

    @Override
    @Transactional
    public String updateStock(String code) {
        logger.info("Service Begin ... xid: " + RootContext.getXID());
        System.out.println("stock code: " + code);
        stockDAO.updateStock(code, 1);
        int stockCount = stockDAO.getStockCount(code);
        return "r-" + code + ":" + stockCount;
    }

    @Override
    @Transactional
    public void putStock(String name, String code) {
        logger.info("Service Begin ... xid: " + RootContext.getXID());
        if (name == null) {
            throw new RuntimeException("name is null");
        }
        if (code == null) {
            throw new RuntimeException("code is null");
        }
        stockDAO.insertStock(new Stock(name, code, 1000L));
    }

    @Override
    public String getStockName(String code) {
        return stockDAO.getStockName(code);
    }
}
